package flex.cc.order.manage.controller;

import java.io.File;
import java.util.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSON;
import flex.cc.PublicUtil;
import flex.cc.core.utils.RequestUtil;
import flex.cc.base.dto.LoginAuthDto;
import flex.cc.basicinformation.entity.ServiceProviderEntity;
import flex.cc.basicinformation.service.ServiceProviderService;
import flex.cc.order.manage.dto.order.OrderImgEntity;
import flex.cc.order.manage.dto.order.OrderMainEntity;
import flex.cc.order.manage.dto.order.OrderPolicyEntity;
import flex.cc.order.manage.dto.order.OrderTrackEntity;
import flex.cc.order.manage.service.OrderPolicyService;
import flex.cc.order.manage.service.OrderRescueService;
import flex.cc.order.manage.service.OrderTrackService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import com.baomidou.mybatisplus.core.metadata.IPage;

import flex.cc.core.support.BaseController;
import flex.cc.order.manage.dto.vo.OrderMainVo;
import flex.cc.order.manage.dto.vo.RescueInforVo;
import flex.cc.order.manage.service.DownLoadService;
import flex.cc.order.manage.service.OrderImgService;
import flex.cc.order.manage.service.OrderMainService;
import flex.cc.util.FileDownloadUtil;
import flex.cc.wrapper.WrapMapper;
import flex.cc.wrapper.Wrapper;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

/**
 * 服务单管理
 */
@RestController
@RequestMapping(value = "/order/manage")
public class OrderManageController extends BaseController {
    @Resource
    private OrderMainService orderMainService;
    @Resource
    private OrderPolicyService orderPolicyService;
    @Resource
    private OrderTrackService orderTrackService;
    @Resource
    private OrderImgService orderImgService;
    @Resource
    private OrderRescueService orderRescueService;
    @Resource
    private DownLoadService downLoadService;
    @Resource
    private ServiceProviderService serviceProviderService;

    /**
	 *
	 * @author WANGCONG
	 * 2021年9月7日下午8:40:41
	 * @desc 服务单分页查询
	 */
    @PostMapping(value = "/queryListWithPage")
    @ApiOperation(httpMethod = "POST", value = "查询服务单列表")
    public Wrapper<IPage<OrderMainVo>> queryOrderListWithPage(@ApiParam(name = "orderMain", value = "服务单信息") @RequestBody Map<String, Object> reqVo) {
        logger.info("查询服务单列表orderMain={}", reqVo);
        OrderMainVo orderMainVo = initVo(reqVo);
        //更新延时单标识
        int cout = orderMainService.batchUpdateDalay(orderMainVo);
        logger.info("更新延时单标识----"+cout);
        LoginAuthDto loginAuthDto = getLoginAuthDto();
        IPage<OrderMainVo> page = orderMainService.queryOrderListWithPage(orderMainVo,loginAuthDto);
        return WrapMapper.ok(page);
    }

    /**
	 *
	 * @author WANGCONG
	 * 2021年9月10日下午12:30:50
	 * @desc 初始化构建查询VO对象
	 */
    @SuppressWarnings({ "unchecked", "rawtypes" })
	public OrderMainVo initVo(Map<String, Object> reqVo) {
    	OrderMainVo orderMainVo = new OrderMainVo();
        orderMainVo.setOrderNo( PublicUtil.isNotEmpty(reqVo.get("orderNo")) ? reqVo.get("orderNo").toString() : null );
        orderMainVo.setOwnerOrderNo( PublicUtil.isNotEmpty(reqVo.get("ownerOrderNo")) ? reqVo.get("ownerOrderNo").toString() : null );
        orderMainVo.setUserName( PublicUtil.isNotEmpty(reqVo.get("userName")) ? reqVo.get("userName").toString() : null );
        orderMainVo.setMobile( PublicUtil.isNotEmpty(reqVo.get("mobile")) ? reqVo.get("mobile").toString() : null );
		orderMainVo.setStartTime( PublicUtil.isNotEmpty(reqVo.get("startTime")) ? reqVo.get("startTime").toString() : null );
		orderMainVo.setEndTime( PublicUtil.isNotEmpty(reqVo.get("endTime")) ? reqVo.get("endTime").toString() : null );
		orderMainVo.setCarNo( PublicUtil.isNotEmpty(reqVo.get("carNo")) ? reqVo.get("carNo").toString() : null ); //W 2022年2月22日16:30:17 车牌号查询条件
		orderMainVo.setRescuerId( PublicUtil.isNotEmpty(reqVo.get("rescuerId")) ? reqVo.get("rescuerId").toString() : null ); //W 2022年2月23日16:16:42 救援商查询条件
		String status = PublicUtil.isNotEmpty(reqVo.get("status")) ? reqVo.get("status").toString() : null;
		orderMainVo.setSourceName(PublicUtil.isNotEmpty(reqVo.get("sourceName")) ? reqVo.get("sourceName").toString() : null);//W 2022年4月13日16:33:01 渠道来源查询条件
		String serviceItem = PublicUtil.isNotEmpty(reqVo.get("serviceItem")) ? reqVo.get("serviceItem").toString() : null;
        if(StringUtils.isNotEmpty(status)){
        	orderMainVo.setStatusArr(status.split(","));
        }
        if(StringUtils.isNotEmpty(serviceItem)){
        	orderMainVo.setServiceItemArr(serviceItem.split(","));
        }
        orderMainVo.setSearchMark(reqVo.get("searchMark")+"");
        orderMainVo.setPageNum( Integer.parseInt(String.valueOf(reqVo.get("pageNum"))) );
        orderMainVo.setPageSize( Integer.parseInt(String.valueOf(reqVo.get("pageSize"))) );
        LinkedHashMap<String, String> addrMap = (LinkedHashMap)reqVo.get("addrCounty");
        if (PublicUtil.isNotEmpty(addrMap)) {
        	if(StringUtils.isNotEmpty(addrMap.get("province"))){
            	orderMainVo.setProvinceArr(addrMap.get("province").split(","));
            }
        	if(StringUtils.isNotEmpty(addrMap.get("city"))){
            	orderMainVo.setCityArr(addrMap.get("city").split(","));
            }
        	if(StringUtils.isNotEmpty(addrMap.get("area"))){
            	orderMainVo.setAreaArr(addrMap.get("area").split(","));
            }
        }
		return orderMainVo;
	}

	/**
	 *
	 * @author WANGCONG
	 * 2021年9月8日下午12:12:36
	 * @desc 服务单部分导出
	 */
	@PostMapping(value = "/exportSelections")
    @ApiOperation(httpMethod = "POST", value = "服务单部分导出")
    public void exportSelections(HttpServletRequest request, HttpServletResponse response, @RequestBody OrderMainVo orderMain){
    	logger.info("服务单部分导出");
    	String dataIds = orderMain.getDataId();
    	System.out.println(dataIds);
    	if(StringUtils.isNotEmpty(dataIds)){
    		orderMain.setDataIdArr(dataIds.split(","));
    		orderMain.setPageNum(1);
    		orderMain.setPageSize(dataIds.split(",").length);

    		String fileParentPath = System.getProperty("user.dir") + File.separator + "order" + File.separator + System.currentTimeMillis();
        	String fileName = "服务单列表";
        	downLoadService.downLoadSelection(request, response, orderMain, fileParentPath, fileName, "1");
        	String filepath = fileParentPath + File.separator + fileName + ".xlsx";
            FileDownloadUtil.downloadByFilepath(request, response, filepath);
        }
    }


	@PostMapping(value = "/exportAll")
    @ApiOperation(httpMethod = "POST", value = "服务单全部导出")
    public void exportAll(HttpServletRequest request, HttpServletResponse response,
    		@ApiParam(name = "reqVo", value = "请求信息") @RequestBody Map<String, Object> reqVo){
    	logger.info("服务单全部导出requestVo={}", reqVo);
    	OrderMainVo orderMain = initVo(reqVo);
    	orderMain.setPageNum(1);
    	if(Integer.parseInt(String.valueOf(reqVo.get("total")))== 0){
    		orderMain.setPageSize( 999 );
    	}else{
    		orderMain.setPageSize( Integer.parseInt(String.valueOf(reqVo.get("total"))) );
    	}
    	String fileParentPath = System.getProperty("user.dir") + File.separator + "order" + File.separator + System.currentTimeMillis();
        String fileName = "服务单列表";
        downLoadService.downLoadSelection(request, response, orderMain, fileParentPath, fileName, "2");
        String filepath = fileParentPath + File.separator + fileName + ".xlsx";
        FileDownloadUtil.downloadByFilepath(request, response, filepath);
    }

    /**
     * @description 车辆信息
     * @param orderNo 服务单号
     * @return
     * @author wkangle
     * @time 2021-09-08 18:31:07
     * @exception/throws
     */
    @PostMapping(value = "/showVehicleMsg/{orderNo}")
    @ResponseBody
    @ApiOperation(httpMethod = "POST", value = "车辆信息")
    public Wrapper<String> showVehicleMsg(@ApiParam(name = "reqVo", value = "请求信息") @PathVariable String orderNo) {
        logger.info("OrderManageController -- showVehicleMsg() ====> {}", orderNo);
        Map<String, Object> result = new HashMap<String, Object>();
        if(PublicUtil.isNotEmpty(orderNo)){
            Map<String, Object> orderPolicyEntityParams = new HashMap<String, Object>();
            orderPolicyEntityParams.put("orderNo", orderNo);
            OrderPolicyEntity orderPolicyEntity = orderPolicyService.getOneByParams(orderPolicyEntityParams);
            result.put("responseCode", "00");
            result.put("responseMsg", orderPolicyEntity);
        } else {
            result.put("responseCode", "01");
            result.put("responseMsg", "服务单号为空");
        }
        return WrapMapper.ok(JSON.toJSONString(result));
    }

    /**
     * @description 备注信息
     * @param orderNo 服务单号
     * @return
     * @author wkangle
     * @time 2021/09/08 0008 13:53
     * @exception/throws
     */
    @PostMapping(value = "/showRemarks/{orderNo}")
    @ResponseBody
    @ApiOperation(httpMethod = "POST", value = "备注信息")
    public Wrapper<String> showRemarks(@ApiParam(name = "reqVo", value = "请求信息") @PathVariable String orderNo) {
        logger.info("OrderManageController -- showRemarks() ====> {}", orderNo);
        Map<String, Object> result = new HashMap<String, Object>();
        if(PublicUtil.isNotEmpty(orderNo)){
            Map<String, Object> orderMainEntityParams = new HashMap<String, Object>();
            orderMainEntityParams.put("orderNo", orderNo);
            OrderMainEntity orderMainEntity = orderMainService.getOneByParams(orderMainEntityParams);

            if (PublicUtil.isNotEmpty(orderMainEntity)){
                Map<String, Object> orderTrackEntityParams = new HashMap<String, Object>();
                orderTrackEntityParams.put("orderNo", orderNo);
                List<OrderTrackEntity> orderTrackEntityList = orderTrackService.getListByParams(orderTrackEntityParams);
                Map<String, Object> responseMsg = new HashMap<String, Object>();
                responseMsg.put("0", orderMainEntity);
                responseMsg.put("1", orderTrackEntityList);
                result.put("responseCode", "00");
                result.put("responseMsg", responseMsg);
            } else {
                result.put("responseCode", "01");
                result.put("responseMsg", "服务单号为空");
            }
        } else {
            result.put("responseCode", "01");
            result.put("responseMsg", "请求参数为空");
        }
        return WrapMapper.ok(JSON.toJSONString(result));
    }

    /**
	 *
	 * @author WANGCONG
	 * 2021年9月9日上午09:24:20
     * @throws Exception
	 * @desc 服务单---展示相关图片
	 */
    @PostMapping(value = "/showImg/{orderNo}")
    @ApiOperation(httpMethod = "POST", value = "查看相关图片")
    public Wrapper<List<OrderImgEntity>> showImg(@ApiParam(name = "reqVo", value = "请求信息") @PathVariable String orderNo) throws Exception{
    	//String ip = InetAddress.getLocalHost().getHostAddress();
    	logger.info("OrderManageController -- showImg() ====> {}", orderNo);
    	if (PublicUtil.isNotEmpty(orderNo)){
    		List<OrderImgEntity> imgList = orderImgService.queryImgByOrderNo(orderNo);
    		imgList.forEach(object -> object.setUrl("/file/pictures" + object.getLocalUrl()));
        	return WrapMapper.ok(imgList);
    	}
    	return WrapMapper.error("参数为空");
    }

    /**
	 *
	 * @author WANGCONG
	 * 2021年9月9日上午09:58:35
	 * @desc 服务单---展示救援信息
	 */
    @GetMapping(value = "/showRescueInfor/{orderNo}")
    @ApiOperation(httpMethod = "GET", value = "查看救援信息")
    public Wrapper<RescueInforVo> showRescueInfor(@ApiParam(name = "reqVo", value = "请求信息") @PathVariable String orderNo){
    	logger.info("OrderManageController -- showRescueInfor() ====> {}", orderNo);
    	if (PublicUtil.isNotEmpty(orderNo)){
    		RescueInforVo vo = orderRescueService.queryRescueInforByOrderNo(orderNo);
    		if(vo!=null && PublicUtil.isNotEmpty(vo.getEnvironment())){
    			vo.setEnvironment(transEnv(vo.getEnvironment()));
    		}else{
    			vo.setEnvironment("");
    		}
        	return WrapMapper.ok(vo);
    	}
    	return WrapMapper.ok();
    }

    /**
	 *
	 * @author WANGCONG
	 * 2021年9月14日上午09:23:38
	 * @desc 救援环境数字代码转换成中文描述，与上游保持一致
	 */
    public String transEnv(String environment) {
    	String result = "";
    	switch (environment) {
		case "1":
			result = "地下停车场拖车";
			break;
		case "2":
			result = "高层停车场拖车";
			break;
		case "3":
			result = "吊装救援";
			break;
		default:
			break;
		}
    	return result;
	}

	/**
	 *
	 * @author WANGCONG
	 * 2021年9月9日上午10:16:20
	 * @desc 服务单---展示救援轨迹
	 */
    @GetMapping(value = "/rescueTrack/{orderNo}")
    @ApiOperation(httpMethod = "GET", value = "查看救援轨迹")
    public Wrapper<List<OrderTrackEntity>> rescueTrack(@ApiParam(name = "reqVo", value = "请求信息") @PathVariable String orderNo){
    	if (PublicUtil.isNotEmpty(orderNo)){
    		Map<String, Object> params = new HashMap<String, Object>();
        	params.put("orderNo", orderNo);
        	params.put("trackType", "01"); //轨迹类型：下单备注00、救援轨迹01、催单备注02、取消备注03
        	List<OrderTrackEntity> rescueTrackList = orderTrackService.getListByParams(params);
        	return WrapMapper.ok(rescueTrackList);
    	}
    	return WrapMapper.ok();
    }

    /**
     * @description 保存备注
     * @param orderMainEntity 服务单id + 备注信息
     * @return
     * @author wkangle
     * @time 2021/09/08 0008 13:53
     * @exception/throws
     */
    @PostMapping(value = "/saveRemark")
    @ResponseBody
    @ApiOperation(httpMethod = "POST", value = "保存备注")
    public Wrapper<String> saveRemark(@ApiParam(name = "reqVo", value = "请求信息") @RequestBody OrderMainEntity orderMainEntity) {
        logger.info("OrderManageController -- showRemarks() ====> {}", orderMainEntity);
        Map<String, Object> result = new HashMap<String, Object>();

        OrderMainEntity newOrderMainEntity = new OrderMainEntity();
        newOrderMainEntity.setDataId(orderMainEntity.getDataId());
        newOrderMainEntity.setRemark(orderMainEntity.getRemark());
        newOrderMainEntity.setUpdateTime(new Date());
        newOrderMainEntity.setUpdater(RequestUtil.getLoginUser().getUserCode());

        int update = orderMainService.update(newOrderMainEntity);
        if (update == 1){
            result.put("responseCode", "00");
            result.put("responseMsg", "修改备注成功");
        } else {
            result.put("responseCode", "01");
            result.put("responseMsg", "修改备注失败");
        }
        return WrapMapper.ok(JSON.toJSONString(result));
    }

    /**
	*
	* @author WANGCONG
	* 2021年10月20日上午11:02:57
	* @desc 手动派单、改派，根据所选服务单的服务类型、省市区集合匹配服务商
	*/
    @PostMapping(value = "/findMatchServicer/{dataIds}")
    @ResponseBody
    @ApiOperation(httpMethod = "POST", value = "查找匹配的服务商")
    @SuppressWarnings({ "rawtypes", "unchecked" })
    public Wrapper<List<ServiceProviderEntity>> findMatchServicer(@ApiParam(name = "reqVo", value = "请求信息") @PathVariable String dataIds){
    	logger.info("OrderManageController -- findMatchServicer() ====> {}", dataIds);
    	OrderMainVo orderMain = new OrderMainVo();
    	if(StringUtils.isNotEmpty(dataIds)){
    		orderMain.setDataIdArr(dataIds.split(","));
        }
    	//根据dataId集合查询服务单主表信息matchRule
    	List<OrderMainVo> orderList = orderMainService.matchRule(orderMain);
    	Set serviceItemSet = new HashSet(); //服务类型
    	Set provinceSet = new HashSet(); //省
    	Set citySet = new HashSet(); //市
    	Set areaSet = new HashSet(); //区
    	for(OrderMainVo order : orderList) {
            // 2022-03-16 16:54:41【2.2-服务包配置需求】省市区及服务项目参数调用trim()，去掉空格，避免查询时因为有空格导致查不到数据
    		//serviceItemSet.add(order.getServiceItem().trim());
    		//provinceSet.add(order.getProvince().trim());
    		//citySet.add(order.getCity().trim());
    		//areaSet.add(order.getDistrict().trim());
			if (PublicUtil.isNotEmpty(order.getServiceItem()))
				serviceItemSet.add(order.getServiceItem().trim());
			if (PublicUtil.isNotEmpty(order.getProvince()))
				provinceSet.add(order.getProvince().trim());
			if (PublicUtil.isNotEmpty(order.getCity()))
				citySet.add(order.getCity().trim());
			if (PublicUtil.isNotEmpty(order.getDistrict()))
				areaSet.add(order.getDistrict().trim());
    	}
    	List<String> serviceItemList = new ArrayList<>(serviceItemSet);
    	List<String> provinceList = new ArrayList<>(provinceSet);
    	List<String> cityList = new ArrayList<>(citySet);
    	List<String> areaList = new ArrayList<>(areaSet);
    	Map<String, Object> params = new HashMap<>();
    	params.put("serviceItemList", serviceItemList);
    	params.put("provinceList", provinceList);
    	params.put("cityList", cityList);
    	params.put("areaList", areaList);
        params.put("status", "1"); /** 2022/02/25 0025 9:56 【2.2-服务包配置需求】查找匹配救援商优化：仅允许启用状态的救援商  */
    	List<ServiceProviderEntity> servicerList = serviceProviderService.findMatchServicer(params);
    	return WrapMapper.ok(servicerList);
    }

    /**
	*
	* @author WANGCONG
	* 2022年3月24日下午14:45:37
	* @desc 手动录单，根据所选服务单的服务类型、省市区集合匹配服务商
	*/
    @PostMapping(value = "/manualMatchServicer")
    @ResponseBody
    @ApiOperation(httpMethod = "POST", value = "手工录单查找匹配的服务商")
    @SuppressWarnings({ "rawtypes", "unchecked" })
    public Wrapper<List<ServiceProviderEntity>> manualMatchServicer( @ApiParam(name = "reqVo", value = "请求信息") @RequestBody Map<String, Object> reqVo ){
    	logger.info("OrderManageController -- manualMatchServicer() ====> {}", reqVo);
    	Set serviceItemSet = new HashSet(); //服务类型
    	Set provinceSet = new HashSet(); //省
    	Set citySet = new HashSet(); //市
    	Set areaSet = new HashSet(); //区
    	serviceItemSet.add(reqVo.get("serviceItem"));
		provinceSet.add(reqVo.get("province"));
		citySet.add(reqVo.get("city"));
		areaSet.add(reqVo.get("area"));
    	List<String> serviceItemList = new ArrayList<>(serviceItemSet);
    	List<String> provinceList = new ArrayList<>(provinceSet);
    	List<String> cityList = new ArrayList<>(citySet);
    	List<String> areaList = new ArrayList<>(areaSet);
    	Map<String, Object> params = new HashMap<>();
    	params.put("serviceItemList", serviceItemList);
    	params.put("provinceList", provinceList);
    	params.put("cityList", cityList);
    	params.put("areaList", areaList);
        params.put("status", "1"); //查找匹配救援商优化：仅允许启用状态的救援商
    	List<ServiceProviderEntity> servicerList = serviceProviderService.findMatchServicer(params);
    	return WrapMapper.ok(servicerList);
    }

}
